import { defineStore } from 'pinia';
import http from '@/utils/http/http.js';
import { useUserStore } from './user';

export const useOrderStore = defineStore('order', {
  state: () => ({
    orders: [],
    currentOrder: null,
    loading: false,
    error: null
  }),
  
  getters: {
    // 获取不同状态的订单数量
    pendingPaymentCount: (state) => state.orders.filter(order => order.status === 0).length,
    pendingShipmentCount: (state) => state.orders.filter(order => order.status === 1).length,
    pendingReceiptCount: (state) => state.orders.filter(order => order.status === 2).length,
    completedCount: (state) => state.orders.filter(order => order.status === 3).length
  },
  
  actions: {
    // 创建订单
    async createOrder(orderData) {
      this.loading = true;
      this.error = null;
      
      try {
        const userStore = useUserStore();
        const isLoggedIn = userStore.isLoggedIn;
        const token = userStore.token;
        
        if (!isLoggedIn || !token) {
          throw new Error('用户未登录');
        }
        
        const response = await http.post('/api/orders/create', orderData, {
          header: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (response.code === 200) {
          return response.data; // 返回订单号
        } else {
          throw new Error(response.message || '创建订单失败');
        }
      } catch (error) {
        this.error = error.message || '创建订单失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 支付订单
    async payOrder(orderNo, paymentType = 1) {
      this.loading = true;
      this.error = null;
      
      try {
        const userStore = useUserStore();
        const isLoggedIn = userStore.isLoggedIn;
        const token = userStore.token;
        
        if (!isLoggedIn || !token) {
          throw new Error('用户未登录');
        }
        
        const paymentData = {
          orderNo,
          paymentType
        };
        
        const response = await http.post('/api/orders/pay', paymentData, {
          header: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (response.code === 200) {
          return true;
        } else {
          throw new Error(response.message || '支付订单失败');
        }
      } catch (error) {
        this.error = error.message || '支付订单失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 获取订单列表
    async fetchOrders(pageNum = 1, pageSize = 10) {
      this.loading = true;
      this.error = null;
      
      try {
        const userStore = useUserStore();
        const isLoggedIn = userStore.isLoggedIn;
        const token = userStore.token;
        
        if (!isLoggedIn || !token) {
          throw new Error('用户未登录');
        }
        
        const response = await http.get(`/api/orders/list?pageNum=${pageNum}&pageSize=${pageSize}`, {
          header: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (response.code === 200 && response.data) {
          this.orders = response.data.list || [];
          return response.data;
        } else {
          throw new Error(response.message || '获取订单列表失败');
        }
      } catch (error) {
        this.error = error.message || '获取订单列表失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 获取订单详情
    async fetchOrderDetail(orderNo) {
      this.loading = true;
      this.error = null;
      
      try {
        const userStore = useUserStore();
        const isLoggedIn = userStore.isLoggedIn;
        const token = userStore.token;
        
        if (!isLoggedIn || !token) {
          throw new Error('用户未登录');
        }
        
        const response = await http.get(`/api/orders/detail/${orderNo}`, {
          header: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (response.code === 200 && response.data) {
          this.currentOrder = response.data;
          return response.data;
        } else {
          throw new Error(response.message || '获取订单详情失败');
        }
      } catch (error) {
        this.error = error.message || '获取订单详情失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 取消订单
    async cancelOrder(orderNo) {
      this.loading = true;
      this.error = null;
      
      try {
        const userStore = useUserStore();
        const isLoggedIn = userStore.isLoggedIn;
        const token = userStore.token;
        
        if (!isLoggedIn || !token) {
          throw new Error('用户未登录');
        }
        
        const response = await http.post(`/api/orders/cancel/${orderNo}`, {}, {
          header: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (response.code === 200) {
          // 更新本地订单状态
          const index = this.orders.findIndex(order => order.orderNo === orderNo);
          if (index !== -1) {
            this.orders[index].status = 4; // 已取消
          }
          return true;
        } else {
          throw new Error(response.message || '取消订单失败');
        }
      } catch (error) {
        this.error = error.message || '取消订单失败';
        throw error;
      } finally {
        this.loading = false;
      }
    },
    
    // 确认收货
    async confirmReceipt(orderNo) {
      this.loading = true;
      this.error = null;
      
      try {
        const userStore = useUserStore();
        const isLoggedIn = userStore.isLoggedIn;
        const token = userStore.token;
        
        if (!isLoggedIn || !token) {
          throw new Error('用户未登录');
        }
        
        const response = await http.post(`/api/orders/confirm/${orderNo}`, {}, {
          header: {
            'Authorization': `Bearer ${token}`
          }
        });
        
        if (response.code === 200) {
          // 更新本地订单状态
          const index = this.orders.findIndex(order => order.orderNo === orderNo);
          if (index !== -1) {
            this.orders[index].status = 3; // 已完成
          }
          return true;
        } else {
          throw new Error(response.message || '确认收货失败');
        }
      } catch (error) {
        this.error = error.message || '确认收货失败';
        throw error;
      } finally {
        this.loading = false;
      }
    }
  }
});